package com.studykun.client.model;

import com.studykun.client.model.js.JsCard;
import com.studykun.client.util.Observable;
import com.studykun.client.util.ObservableHandler;
import com.studykun.client.util.ObservableHandlers;

public class Card implements Observable<Card> {
  private String kanji_;
  private String hiragana_;
  private String english_;
  private boolean selected_;
  private int progress_;
  private ObservableHandlers<Card> observableHandlers_ =
    new ObservableHandlers<Card>(); 
  
  public Card(
      final JsCard jsCard) {
    kanji_ = jsCard.kanji();
    hiragana_ = jsCard.hiragana();
    english_ = jsCard.english();
    progress_ = jsCard.progress();
    selected_ = jsCard.selected();
  }
  
  public String kanjiClean() {
    return kanji_.replaceAll("＿", "");
  }
  
  public String kanji() {
    return kanji_;
  }
  
  public String kanji(
      final String kanji) {
    final String oldKanji = kanji_;
    kanji_ = kanji;
    if (oldKanji != kanji) {
      observableHandlers_.firePropertyChanged(this, "kanji", oldKanji, kanji);
    }
    return kanji;
  }
  
  public String hiragana() {
    return hiragana_;
  }
  
  public String hiragana(
      final String hiragana) {
    final String oldHiragana = hiragana_;
    hiragana_ = hiragana;
    if (oldHiragana != hiragana) {
      observableHandlers_.firePropertyChanged(this, "hiragana", oldHiragana, hiragana);
    }
    return hiragana;
  }
  
  public String english() {
    return english_;
  }
  
  public String english(
      final String english) {
    final String oldEnglish = english_;
    english_ = english;
    if (oldEnglish != english) {
      observableHandlers_.firePropertyChanged(this, "english", oldEnglish, english);
    }
    return english;
  }
  
  public int progress() {
    return progress_;
  }
  
  public int progress(
      final int progress) {
    final int oldProgress = progress_;
    progress_ = progress;
    if (oldProgress != progress) {
      observableHandlers_.firePropertyChanged(this, "progress", oldProgress, progress);
    }
    return progress;
  }
  
  public boolean selected() {
    return selected_;
  }
  
  public boolean selected(
      final boolean selected) {
    final boolean oldSelected = selected_;
    selected_ = selected;
    if (oldSelected != selected) {
      observableHandlers_.firePropertyChanged(this, "selected", oldSelected, selected);
    }
    return selected;
  }

  public final int adjustProgress(
      final int offset) {
    final int newProgress = Math.min(Math.max(progress() + offset, 0), 4);
    progress(newProgress);
    return newProgress;
  }

  public void addObservableHandler(
      final ObservableHandler<Card> handler) {
    observableHandlers_.addObservableHandler(handler);
  }

  public void removeObservableHandler(
      final ObservableHandler<Card> handler) {
    observableHandlers_.removeObservableHandler(handler);
  }
}
